package com.simple.cms.core.shiro;

import com.simple.cms.common.enums.ResultCode;
import com.simple.cms.common.exception.BizException;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

/**
 * @author kin
 * @since 2017/8/10
 */
public class StatelessRealm extends AuthorizingRealm {

    @Override
    public boolean supports(AuthenticationToken token) {
        //仅支持StatelessToken类型的Token
        return token instanceof StatelessToken;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        StatelessToken statelessToken = (StatelessToken) authenticationToken;
        String userName = (String) statelessToken.getPrincipal();
        String credentials = (String) statelessToken.getCredentials();

        if (StringUtils.isEmpty(getKey(credentials))) {
            throw new CredentialsException();
        }


        return new SimpleAuthenticationInfo(
                userName, //用户名
                credentials,
                getName()  //realm name
        );
    }

    private String getKey(String token) {//得到密钥，此处硬编码一个
        if ("123456".equals(token)) {
            return "admin";
        }
        return null;
    }
}
